﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
using System.Windows;
using System.Diagnostics;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Net;

namespace Win7ThemeEditor
{
    public partial class MainWindow : GlassWindow
    {
        #region 全局变量 global variable

        string defico = "(默认图标)", defimg = "(无)", defcur = "（默认指针）", defwav = "（无）", defcolor = "#80FFFFFF";
        string definfo = "作者：\r\n网址：";
        string defRarInfo = "【安装提示】\r\n\r\n●请务必保证系统为Win7家庭高级版以上（包括专业版和旗舰版，不知道的可以到我的电脑右键属性里查看），并打过主题破解补丁和文件夹背景补丁。没打过补丁的请参阅下面的网址： http://bbs.comicdd.com/thread-199748-1-1.html \r\n\r\n●此安装包为直装版，需要删除的请在个性化设置里右键删除。\r\n\r\n●下面的路径无需更改，直接安装即可！";
        string defAboutInfo = "Copyright 2011 樱茶幻萌组@桂叶出品\n樱茶Win7主题生成器 " + CommonData.VER + "\n本软件可自由传播使用，但禁止用于任何商业用途，最终解释权归樱茶幻萌组\n软件作者：桂叶君    最后更新：2012-2-28";
        string themeFile = "";
        string openTheme = "";
        string openThemeDir = "";
        int[] sliderTime = { 10000, 30000, 60000, 180000, 300000, 600000, 900000, 1200000, 1800000, 3600000, 7200000, 10800000, 14400000, 21600000, 43200000, 86400000 };
        string[] cbSysWaveDefaultNum = { "800", "801", "810", "811", "812", "813", "814", "815", "816", "817", "818", "819", "820", "821", "822" };
        string tempDir = Environment.CurrentDirectory + @"\WinRAR\Temp\";
        string tempDir2 = Environment.CurrentDirectory + @"\WinRAR\Temp2\";
        string rarPath = Environment.CurrentDirectory + @"\WinRAR\Rar.exe";
        string currentDir = System.Environment.CurrentDirectory;
        string tempDir3 = Environment.CurrentDirectory + @"\Temp\";
        string sysThemeDir = Environment.GetEnvironmentVariable("windir") + @"\Resources\Themes\";
        #endregion

        //显示错误
        private void showErrorWindow(string errStr)
        {
            tbError.Text = errStr;
            ShowErrorWindowSB.Begin();
        }

        //显示对话框
        private void showDialog(string title,string contant,string button1,string button2)
        {

        }

        //文件选择对话框，显示路径
        private void fileDialogDir(TextBox tb,string ext)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.RestoreDirectory = true;
            switch (ext)
            {
                case "cur":
                    op.Filter = "指针图像文件cur,ani|*.cur;*.ani";break;
                case "ico":
                    op.Filter = "ICO文件|*.ico";break;
                case "jpg":
                    op.Filter = "图像文件(JPG)|*.jpg|所有文件(*.*)|*.*";break;
                case "png":
                    op.Filter = "图像文件(PNG)|*.png|所有文件(*.*)|*.*"; break;
                case "img":
                    op.Filter = "图像文件(jpg,png,bmp,gif)|*.png;*.jpg;*.bmp;*.gif|所有文件(*.*)|*.*"; break;
                case "mss":
                    op.Filter = "主题样式文件(*.Msstyles)|*.msstyles";break;
                case "wav":
                    op.Filter = "波形文件Wav|*.wav"; break;
                default:
                    return;

            }
            op.ShowDialog();
            if (op.FileName != "")
            {
                tb.Text = op.FileName;
                if (ext == "cur")
                {
                    System.Windows.Input.Cursor cur = new System.Windows.Input.Cursor(op.FileName);
                    tb.Cursor = cur;
                }
            }
        }

        //添加壁纸，显示路径
        private void addWallpaper()
        {
            OpenFileDialog op = new OpenFileDialog();
            op.RestoreDirectory = true;
            op.Multiselect = true;
            op.Filter = "图像文件(jpg,png,bmp,gif)|*.jpg;*.png;*.bmp;*.gif|所有文件(*.*)|*.*";
            op.ShowDialog();
            if (op.FileName != "")
            {
                foreach (string name in op.FileNames)
                {
                    wps.Add(new WallpaperItems { Name = name, Pic = name });
                    
                }
            }
        }

        //检测图片数量
        private void detectWallpaperNum()
        {
            if (wps.Count > 1)
            {
                cbWallpaperTime.IsEnabled = true;
                cbShuffle.IsEnabled = true;
            }
            else 
            { 
                cbWallpaperTime.IsEnabled = false;
                cbShuffle.IsEnabled = false;
            }
        }

        //设置新建
        public void setDefault()
        {
            try
            {
                sbNewTheme.Begin();
            }
            catch { }
            //基本信息
            tbMssfileDir.Text = "";
            tbLogoDir.Text = defimg;
            tbInfo.Text = definfo;
            if (File.Exists(sysThemeDir + "Aero\\aero.msstyles"))
                tbMssfileDir.Text = sysThemeDir + "Aero\\aero.msstyles";
            tbThemeName.Text = "我的主题";
            tbFileName.Text = "My Theme";

            //系统图标
            tbIconComputertfileDir.Text = defico;
            tbIconUserDir.Text = defico;
            tbIconNetworkDir.Text = defico;
            tbIconDustEmptyDir.Text = defico;
            tbIconDustFullDir.Text = defico;
            
            //系统指针
            for (int i = 1; i <= 15; i++)
            {
                ((TextBox)FindName("tbcur" + i.ToString())).Text = defcur;
            }
            tbcur1.Cursor = System.Windows.Input.Cursors.AppStarting;
            tbcur2.Cursor  = System.Windows.Input.Cursors.Arrow;
            tbcur3.Cursor  = System.Windows.Input.Cursors.Cross;
            tbcur4.Cursor  = System.Windows.Input.Cursors.Hand;
            tbcur5.Cursor  = System.Windows.Input.Cursors.Help;
            tbcur6.Cursor  = System.Windows.Input.Cursors.IBeam;
            tbcur7.Cursor  = System.Windows.Input.Cursors.No;
            tbcur8.Cursor  = System.Windows.Input.Cursors.Pen;
            tbcur9.Cursor  = System.Windows.Input.Cursors.SizeAll;
            tbcur10.Cursor  = System.Windows.Input.Cursors.SizeNESW;
            tbcur11.Cursor  = System.Windows.Input.Cursors.SizeNS;
            tbcur12.Cursor  = System.Windows.Input.Cursors.SizeNWSE;
            tbcur13.Cursor  = System.Windows.Input.Cursors.SizeWE;
            tbcur14.Cursor  = System.Windows.Input.Cursors.UpArrow;
            tbcur15.Cursor  = System.Windows.Input.Cursors.Wait;


            //背景壁纸

            wps.Clear();
            cbWallpaperTime.SelectedIndex = 5;
            cbWallpaperTime.IsEnabled = false;
            cbShuffle.IsChecked = false;
            cbShuffle.IsEnabled = false;

            //窗口颜色
            rtgColor1_MouseLeftButtonDown(null,null);

            //系统音
            for (int i = 0; i < sysWaveItems.Count; i++)
            {
                sysWaveItems[i].Custom = "0";
                sysWaveItems[i].Path = null;
            }
            listboxSysWaveItems.Items.Refresh();
            chboxDefwav.IsChecked = true;
            cbSysWaveDefault.SelectedIndex = 0;
            enableWave(false);

            //自解压框
            checkboxSaveRarKey.IsChecked = false;
            tbSaveRarKey.IsEnabled = false;
            tbSaveRarKey.Text = "";
            tbSaveRarInfo.Text = defRarInfo;
            checkboxSaveRarAutoRun.IsChecked = false;
            tbSaveRarTitle.Text = "";
            
        }

        //非法名称除错
        private void replaceFileName(System.Windows.Controls.TextBox tb)
        {
            tb.Text = tb.Text.Replace(";", "").Replace(":", "").Replace("<", "").Replace(">", "").Replace("*", "").Replace("?", "").Replace("\\", "").Replace("/", "").Replace("|", "").Replace("\"", "").Replace("[","").Replace("]","").Replace(";","");
        }
        
        //显示图标、图片
        private void setImage(Image img, string path)
        {
            if (path == defico)
            {
                if (img == icoComputer)
                {
                    icoComputer.Source = new BitmapImage(new Uri("/Win7ThemeEditor;component/Res/Icon/Computer.png", UriKind.Relative));
                }
                else if (img == icoUserFile)
                {
                    icoUserFile.Source = new BitmapImage(new Uri("/Win7ThemeEditor;component/Res/Icon/UserFile.png", UriKind.Relative));
                }
                else if (img == icoNetwork)
                    icoNetwork.Source = new BitmapImage(new Uri("/Win7ThemeEditor;component/Res/Icon/Network.png", UriKind.Relative));
                else if (img == icoDustEmpty)
                    icoDustEmpty.Source = new BitmapImage(new Uri("/Win7ThemeEditor;component/Res/Icon/DustEmpty.png", UriKind.Relative));
                else if (img == icoDustFull)
                    icoDustFull.Source = new BitmapImage(new Uri("/Win7ThemeEditor;component/Res/Icon/DustFull.png", UriKind.Relative));
            }
            else
            {
                try
                {
                    img.Source = new BitmapImage(new Uri(path, UriKind.Absolute));
                }
                catch { }
            }
        }
        
        //打开theme文件
        private void openThmeFile()
        {
            DirectoryInfo dir = new DirectoryInfo(sysThemeDir);
            FileInfo[] files = (dir).GetFiles();
            themeDirFileItems.Clear();
            foreach (FileInfo file in files)
            {
                if (Path.GetExtension(file.FullName.ToLower())==".theme")
                {
                    var ini = new Class.IniFile(file.FullName);
                    string FullNameTemp="";
                    string DisplayName =ini.ReadInivalue("Theme", "DisplayName");
                    FullNameTemp +="文件名："+file.Name+"\n";
                    if (DisplayName != "")
                        FullNameTemp += "主题名称：" + ini.ReadInivalue("Theme", "DisplayName");
                    string imgFile = relpaceSr(ini.ReadInivalue(@"Control Panel\Desktop", "Wallpaper"));
                    if (!File.Exists(imgFile))
                        imgFile = null;
                    if (DisplayName.IndexOf("themeui.dll") == -1)
                    {
                        
                        themeDirFileItems.Add(new sysThemeFileItems { FullName = file.FullName, SName = FullNameTemp, ImgName = imgFile });
                        
                        
                    }
                }
                
                
            }
        }

        //写入Theme文件内容
        private void addLine(string line)
        {
            themeFile += (line + "\r\n");
        }
        private void writeFile()
        {
            string themeName = tbFileName.Text;
            themeFile = "";
            //主题信息
            addLine(";此主题文件由樱茶Win7主题生成器生成");
            addLine(";" + tbInfo.Text.Replace("\r\n", "\r\n;"));
            addLine("");
            addLine("[Theme]\r\n; Windows 7 - IDS_THEME_DISPLAYNAME_AERO");
            addLine("DisplayName=" + tbThemeName.Text);
            if (tbLogoDir.Text != defimg) addLine(@"BrandImage=%SystemRoot%\Resources\Themes\" + themeName + @"\Logo.png");
            addLine("");

            //icon
            addLine("; Computer - SHIDI_SERVER\r\n[CLSID\\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\DefaultIcon]");
            if (tbIconComputertfileDir.Text != defico) 
                addLine(@"DefaultValue=%SystemRoot%\resources\themes\" + themeName + @"\Icon\Computer.ico");
            else 
                addLine(@"DefaultValue=%SystemRoot%\System32\imageres.dll,-109");
            addLine("");
            addLine("; UsersFiles - SHIDI_USERFILES\r\n"+@"[CLSID\{59031A47-3F72-44A7-89C5-5595FE6B30EE}\DefaultIcon]");
            if (tbIconUserDir.Text != defico)
                addLine(@"DefaultValue=%SystemRoot%\resources\themes\"+themeName+@"\Icon\UsersFiles.ico");
            else
                addLine(@"DefaultValue=%SystemRoot%\System32\imageres.dll,-123");
            addLine("");
            addLine("; Network - SHIDI_MYNETWORK\r\n"+@"[CLSID\{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}\DefaultIcon]");
            if(tbIconNetworkDir.Text!=defico)
                addLine(@"DefaultValue=%SystemRoot%\resources\themes\"+themeName+@"\Icon\Network.ico");
            else
                addLine(@"DefaultValue=%SystemRoot%\System32\imageres.dll,-25");
            addLine(@"; Recycle Bin - SHIDI_RECYCLERFULL SHIDI_RECYCLER");
            addLine(@"[CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon]");
            if (tbIconDustFullDir.Text == defico)
                addLine(@"Full=%SystemRoot%\System32\imageres.dll,-54");
            else
                addLine(@"Full=%SystemRoot%\resources\themes\" + themeName + @"\Icon\RecycleFull.ico");
            if (tbIconDustEmptyDir.Text == defico)
                addLine(@"Empty=%SystemRoot%\System32\imageres.dll,-55");
            else
                addLine(@"Empty=%SystemRoot%\resources\themes\" + themeName + @"\Icon\RecycleEmpty.ico");
            addLine("");

            //Cursors
            addLine(@"[Control Panel\Cursors]");
            if (tbcur1.Text == defcur)
                addLine(@"AppStarting=%SystemRoot%\cursors\aero_working.ani" );
            else
                addLine(@"AppStarting=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\AppStarting" + Path.GetExtension(tbcur1.Text));
            if (tbcur2.Text == defcur)
                addLine(@"Arrow=%SystemRoot%\cursors\aero_arrow.cur");
            else
                addLine(@"Arrow=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\Arrow" + Path.GetExtension(tbcur2.Text));
            if (tbcur3.Text == defcur)
                addLine(@"Crosshair=");
            else
                addLine(@"Crosshair=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\Crosshair" + Path.GetExtension(tbcur3.Text));
            if (tbcur4.Text == defcur)
                addLine(@"Hand=%SystemRoot%\cursors\aero_link.cur");
            else
                addLine(@"Hand=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\Hand" + Path.GetExtension(tbcur2.Text));
            if (tbcur5.Text == defcur)
                addLine(@"Help=%SystemRoot%\cursors\aero_helpsel.cur");
            else
                addLine(@"Help=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\Help" + Path.GetExtension(tbcur5.Text));
            if (tbcur6.Text == defcur)
                addLine(@"IBeam=");
            else
                addLine(@"IBeam=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\IBeam" + Path.GetExtension(tbcur6.Text));
            if (tbcur7.Text == defcur)
                addLine(@"No=%SystemRoot%\cursors\aero_unavail.cur");
            else
                addLine(@"No=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\No" + Path.GetExtension(tbcur7.Text));
            if (tbcur8.Text == defcur)
                addLine(@"NWPen=%SystemRoot%\cursors\aero_pen.cur");
            else
                addLine(@"NWPen=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\NWPen" + Path.GetExtension(tbcur8.Text));
            if (tbcur9.Text == defcur)
                addLine(@"SizeAll=%SystemRoot%\cursors\aero_move.cur");
            else
                addLine(@"SizeAll=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\SizeAll" + Path.GetExtension(tbcur9.Text));
            if (tbcur10.Text == defcur)
                addLine(@"SizeNESW=%SystemRoot%\cursors\aero_nesw.cur");
            else
                addLine(@"SizeNESW=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\SizeNESW" + Path.GetExtension(tbcur10.Text));
            if (tbcur11.Text == defcur)
                addLine(@"SizeNS=%SystemRoot%\cursors\aero_ns.cur");
            else
                addLine(@"SizeNS=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\SizeNS" + Path.GetExtension(tbcur11.Text));
            if (tbcur12.Text == defcur)
                addLine(@"SizeNWSE=%SystemRoot%\cursors\aero_nwse.cur");
            else
                addLine(@"SizeNWSE=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\SizeNWSE" + Path.GetExtension(tbcur12.Text));
            if (tbcur13.Text == defcur)
                addLine(@"SizeWE=%SystemRoot%\cursors\aero_ew.cur");
            else
                addLine(@"SizeWE=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\SizeWE" + Path.GetExtension(tbcur13.Text));
            if (tbcur14.Text == defcur)
                addLine(@"UpArrow=%SystemRoot%\cursors\aero_up.cur");
            else
                addLine(@"UpArrow=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\UpArrow" + Path.GetExtension(tbcur14.Text));
            if (tbcur15.Text == defcur)
                addLine(@"Wait=%SystemRoot%\cursors\aero_busy.ani");
            else
                addLine(@"Wait=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\Wait" + Path.GetExtension(tbcur15.Text));
            addLine(@"DefaultValue="+themeName+" Cursors");
            addLine(@"DefaultValue.MUI=@main.cpl,-1020");
            addLine("");

            //wallpaper
            addLine(@"[Control Panel\Desktop]");
            if (wps.Count == 0)
                addLine(@"Wallpaper=%SystemRoot%\web\wallpaper\Windows\img0.jpg");
            else
                addLine(@"Wallpaper=%SystemRoot%\Resources\Themes\" + themeName + @"\Wallpapers\0"+Path.GetExtension(wps[0].Name));
            addLine(@"TileWallpaper=0");
            addLine("WallpaperStyle=10");
            addLine("Pattern=");
            addLine("");

            //mss
            addLine("[VisualStyles]");
            addLine(@"Path=%SystemRoot%\resources\Themes\" + themeName +@"\" + themeName + ".msstyles");
            addLine("ColorStyle=NormalColor");
            addLine("Size=NormalSize");
            addLine("ColorizationColor=" + tbColorStr.Text.Replace("#", "0x"));
            addLine("Transparency=1");
            addLine("VisualStyleVersion=10");
            addLine("Composition=1");
            addLine("");
            addLine("[boot]\r\nSCRNSAVE.EXE=\r\n\r\n[MasterThemeSelector]\r\nMTSM=DABJDKT\r\n");

            //sound
            addLine("[Sounds]");
            if (chboxDefwav.IsChecked == true) 
            {
                addLine("SchemeName=@%SystemRoot%\\System32\\mmres.dll,-" + cbSysWaveDefaultNum[cbSysWaveDefault.SelectedIndex]);
            }
            else
            {
                addLine("SchemeName=" + themeName + " Sound");
                for (int i = 0; i < sysWaveItems.Count; i++)
                {
                    if (sysWaveItems[i].Path != null && sysWaveItems[i].Path != "")
                    {
                        addLine("[" + sysWaveItems[i].IniName + "]");
                        addLine(@"DefaultValue=%SystemRoot%\Resources\Themes\" + themeName + @"\Sound\" + sysWaveItems[i].IniName.Remove(0, sysWaveItems[i].IniName.LastIndexOf("\\") + 1).Replace(".", "") + ".wav");
                    }
                }

            }

            addLine("");
            
            //slideshow
            if (wps.Count > 1) 
            {
                
                addLine("[Slideshow]");
                addLine("Interval=" + sliderTime[cbWallpaperTime.SelectedIndex]);
                addLine("Shuffle=" + ((cbShuffle.IsChecked == true) ? "1" : "0"));
                addLine(@"ImagesRootPath=%SystemRoot%\resources\Themes\"+themeName+@"\Wallpapers");
                for (int i = 0; i < wps.Count; i++)
                {
                    addLine("Item"+i.ToString()+@"Path==%SystemRoot%\resources\Themes\" + themeName + @"\Wallpapers\"+i.ToString()+Path.GetExtension(wps[i].Name));
                }
            }


        }

        //文件操作
        private void copyFile(string pathFrom,string pathTo,bool isOverwrite)
        {
            FileInfo fi = new FileInfo(pathFrom);
            //判断文件属性是否只读?是则修改为一般属性再操作
            if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
            {
                fi.Attributes = FileAttributes.Normal;
            }
            File.Copy(pathFrom, pathTo, isOverwrite);
        }
        private void creatDir(string dir)
        {
            DirectoryInfo maindir = new DirectoryInfo(dir);
            if (!maindir.Exists)
                maindir.Create();
        }
        public bool IsUsed(string fileName)
        {
            bool result = false;

            try
            {
                FileStream fs = File.OpenWrite(fileName);
                fs.Close();
            }
            catch
            {
                result = true;
            }
            return result;
        }// 判断文件是否被其他程序占用
        private bool fileOperate(string themeSaveDir)
        {
            //themeSaveDir = @"D:\Develop\Test\";//测试用
            string enname = tbFileName.Text;
            
            string themeDir = themeSaveDir + enname + @"\";

            DirectoryInfo diThemeDir = new DirectoryInfo(themeDir);
            
            try
            {
                //目录创建，固定文件
                creatDir(themeDir + @"Cursors\");
                creatDir(themeDir + @"Wallpapers\");
                creatDir(themeDir + @"Icon\");
                creatDir(themeDir + @"Sound\");
                creatDir(themeDir + @"en-US\");
                creatDir(themeDir + @"Shell\NormalColor\en-US\");
                creatDir(themeDir + @"Shell\NormalColor\zh-CN\");
                creatDir(themeDir + @"zh-CN\");
                copyFile(currentDir + @"\Res\File\shellstyle.dll", themeDir + @"Shell\NormalColor\shellstyle.dll", true);
                copyFile(currentDir + @"\Res\File\shellstyle.dll.mui", themeDir + @"Shell\NormalColor\zh-CN\shellstyle.dll.mui", true);
                copyFile(currentDir + @"\Res\File\aero.msstyles.mui", themeDir + @"zh-CN\" + enname + ".msstyles.mui", true);

                //Mss、Theme、logo文件
                string FILE_NAME = themeSaveDir + enname + ".theme";
                using (StreamWriter sw = new StreamWriter(new FileStream(FILE_NAME,FileMode.Create),System.Text.Encoding.Default))
                {
                    sw.Write(themeFile);
                    sw.Close();
                }
                copyFile(tbMssfileDir.Text, themeDir + enname + ".msstyles", true);
                if(tbLogoDir.Text!=defimg)
                    copyFile(tbLogoDir.Text, themeDir + "Logo.png", true);


                //Icon
                if (tbIconComputertfileDir.Text != defico)
                    copyFile(tbIconComputertfileDir.Text, themeDir + @"Icon\Computer.ico", true);
                if (tbIconUserDir.Text != defico)
                    copyFile(tbIconUserDir.Text, themeDir + @"Icon\UsersFiles.ico", true);
                if (tbIconNetworkDir.Text != defico)
                    copyFile(tbIconNetworkDir.Text, themeDir + @"Icon\Network.ico", true);
                if (tbIconDustEmptyDir.Text != defico)
                    copyFile(tbIconDustEmptyDir.Text, themeDir + @"Icon\RecycleEmpty.ico", true);
                if (tbIconDustFullDir.Text != defico)
                    copyFile(tbIconDustFullDir.Text, themeDir + @"Icon\RecycleFull.ico", true);

                //Cursors
                if (tbcur1.Text != defcur)
                    copyFile(tbcur1.Text, themeDir + @"Cursors\AppStarting" + Path.GetExtension(tbcur1.Text), true);
                if (tbcur2.Text != defcur)
                    copyFile(tbcur2.Text, themeDir + @"Cursors\Arrow" + Path.GetExtension(tbcur2.Text), true);
                if (tbcur3.Text != defcur)
                    copyFile(tbcur3.Text, themeDir + @"Cursors\Crosshair" + Path.GetExtension(tbcur3.Text), true);
                if (tbcur4.Text != defcur)
                    copyFile(tbcur4.Text, themeDir + @"Cursors\Hand" + Path.GetExtension(tbcur4.Text), true);
                if (tbcur5.Text != defcur)
                    copyFile(tbcur5.Text, themeDir + @"Cursors\Help" + Path.GetExtension(tbcur5.Text), true);
                if (tbcur6.Text != defcur)
                    copyFile(tbcur6.Text, themeDir + @"Cursors\IBeam" + Path.GetExtension(tbcur6.Text), true);
                if (tbcur7.Text != defcur)
                    copyFile(tbcur7.Text, themeDir + @"Cursors\No" + Path.GetExtension(tbcur7.Text), true);
                if (tbcur8.Text != defcur)
                    copyFile(tbcur8.Text, themeDir + @"Cursors\NWPen" + Path.GetExtension(tbcur8.Text), true);
                if (tbcur9.Text != defcur)
                    copyFile(tbcur9.Text, themeDir + @"Cursors\SizeAll" + Path.GetExtension(tbcur9.Text), true);
                if (tbcur10.Text != defcur)
                    copyFile(tbcur10.Text, themeDir + @"Cursors\SizeNESW" + Path.GetExtension(tbcur10.Text), true);
                if (tbcur11.Text != defcur)
                    copyFile(tbcur11.Text, themeDir + @"Cursors\SizeNS" + Path.GetExtension(tbcur11.Text), true);
                if (tbcur12.Text != defcur)
                    copyFile(tbcur12.Text, themeDir + @"Cursors\SizeNWSE" + Path.GetExtension(tbcur12.Text), true);
                if (tbcur13.Text != defcur)
                    copyFile(tbcur13.Text, themeDir + @"Cursors\SizeWE" + Path.GetExtension(tbcur13.Text), true);
                if (tbcur14.Text != defcur)
                    copyFile(tbcur14.Text, themeDir + @"Cursors\UpArrow" + Path.GetExtension(tbcur14.Text), true);
                if (tbcur15.Text != defcur)
                    copyFile(tbcur15.Text, themeDir + @"Cursors\Wait" + Path.GetExtension(tbcur15.Text), true);

                //Sound
                
                for (int i = 0; i < sysWaveItems.Count; i++)
                {
                    if (sysWaveItems[i].Path != "" && sysWaveItems[i].Path != null)
                    {
                        string tempfilename = sysWaveItems[i].IniName.Remove(0, sysWaveItems[i].IniName.LastIndexOf("\\") + 1).Replace(".", "");
                        
                        copyFile(sysWaveItems[i].Path, themeDir + @"Sound\" + tempfilename + ".wav", true);
                    }
                        
                    
                }

                    //Wallpaper
                    if (wps.Count != 0)
                    {
                        for (int i = 0; i < wps.Count; i++)
                        {
                            copyFile(wps[i].Name, themeDir + @"Wallpapers\" + i.ToString() + Path.GetExtension(wps[i].Name), true);
                        }
                    }

                return true;
            }
            catch (System.Exception ex)
            {
                showErrorWindow(ex.ToString());
                return false;
            }
        }

        //打开读取theme文件内容(2.5）
        private void readThemeFile()
        {
            var ini = new Class.IniFile(openThemeDir);
            string iniText = File.ReadAllText(openThemeDir, Encoding.Default);
            
            //theme
            tbThemeName.Text = ini.ReadInivalue("Theme", "DisplayName");
            tbFileName.Text = Path.GetFileNameWithoutExtension(ini.ReadInivalue("VisualStyles", "Path"));
            if (ini.ReadInivalue("Theme", "BrandImage") != "" && fest(relpaceSr(ini.ReadInivalue("Theme", "BrandImage"))))
                tbLogoDir.Text = relpaceSr(ini.ReadInivalue("Theme", "BrandImage"));
            if (fest(relpaceSr(ini.ReadInivalue("VisualStyles", "Path"))))
                tbMssfileDir.Text = relpaceSr(ini.ReadInivalue("VisualStyles", "Path"));

            tbInfo.Text = iniText.Remove(iniText.IndexOf("\n[")-1).Replace(";","").Replace("此主题文件由樱茶Win7主题生成器生成\r\n","").Replace("\r\n\r\n","");

            //icon
            if (fest(removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\DefaultIcon", "DefaultValue")))))
                tbIconComputertfileDir.Text = removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\DefaultIcon", "DefaultValue")));
            if (fest(removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{59031A47-3F72-44A7-89C5-5595FE6B30EE}\DefaultIcon", "DefaultValue")))))
                tbIconUserDir.Text = removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{59031A47-3F72-44A7-89C5-5595FE6B30EE}\DefaultIcon", "DefaultValue")));
            if (fest(removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}\DefaultIcon", "DefaultValue")))))
                tbIconNetworkDir.Text = removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}\DefaultIcon", "DefaultValue")));
            if (fest(removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon", "Full")))))
                tbIconDustFullDir.Text = removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon", "Full")));
            if (fest(removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon", "Empty")))))
                tbIconDustEmptyDir.Text = removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon", "Empty")));

            //cursor
            string[] cur = new string[15];
            cur[0] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "AppStarting"));
            cur[1] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "Arrow"));
            cur[2] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "Crosshair"));
            cur[3] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "Hand"));
            cur[4] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "Help"));
            cur[5] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "IBeam"));
            cur[6] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "No"));
            cur[7] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "NWPen"));
            cur[8] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "SizeAll"));
            cur[9] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "SizeNESW"));
            cur[10] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "SizeNS"));
            cur[11] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "SizeNWSE"));
            cur[12] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "SizeWE"));
            cur[13] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "UpArrow"));
            cur[14] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", "Wait"));
            for (int i = 1; i <= 15;i++ )
                if (fest(cur[i - 1]))
                {
                    ((TextBox)FindName("tbcur" + i.ToString())).Text = cur[i - 1];
                    try
                    { ((TextBox)FindName("tbcur" + i.ToString())).Cursor = new System.Windows.Input.Cursor(cur[i - 1]); }
                    catch { }
                    
                }

            //wallpaper
            string wp0 = relpaceSr(ini.ReadInivalue(@"Control Panel\Desktop", "Wallpaper"));
            if(fest(wp0))
                wps.Add(new WallpaperItems { Name = wp0, Pic = wp0 });
            string sldir = relpaceSr(ini.ReadInivalue(@"Slideshow", "ImagesRootPath")) + "\\";
            if (Directory.Exists(sldir))
            {
                DirectoryInfo dir = new DirectoryInfo(sldir);
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    //MessageBox.Show(file.FullName);
                    if ((Path.GetExtension(file.FullName).ToLower() == ".jpg"
                        || Path.GetExtension(file.FullName).ToLower() == ".png"
                        || Path.GetExtension(file.FullName).ToLower() == ".bmp"
                        || Path.GetExtension(file.FullName).ToLower() == ".jepg")
                        && file.FullName != wp0)
                        //MessageBox.Show(file.FullName);
                        wps.Add(new WallpaperItems { Name = file.FullName, Pic = file.FullName });
                }

            }

            if (wps.Count > 1)
            {
                cbWallpaperTime.IsEnabled = true;
                cbShuffle.IsEnabled = true;
            }
            else { cbWallpaperTime.IsEnabled = false; }

            if (ini.ReadInivalue(@"Slideshow", "Interval") != "")
            {
                int sltime = Convert.ToInt32(ini.ReadInivalue(@"Slideshow", "Interval"));
                for (int i = 0; i < sliderTime.Length; i++)
                {
                    if (sltime == sliderTime[i])
                        cbWallpaperTime.SelectedIndex = i;
                }
            }
            string shuffle = ini.ReadInivalue(@"Slideshow", "Shuffle");
            if ( shuffle!= "")
            {
                if (shuffle == "0")
                    cbShuffle.IsChecked = false;
                else
                    cbShuffle.IsChecked = true;
            }

            //color
            tbColorStr.Text = "#" +ini.ReadInivalue(@"VisualStyles", "ColorizationColor").ToUpper().Replace("0X", "");
            

            //sound
            bool isCustomWav = false;
            string soundThemeName =relpaceSr(ini.ReadInivalue("Sounds", "SchemeName"));
            if (Path.GetFileName(removedll(soundThemeName)) == "mmres.dll")
            {
                
                string num = soundThemeName.Remove(0, soundThemeName.LastIndexOf("-") + 1);
                int select = 0;
                for (int i = 0; i < cbSysWaveDefault.Items.Count; i++)
                {
                    if (num == cbSysWaveDefaultNum[i])
                        select = i;
                }
                cbSysWaveDefault.SelectedIndex = select;
                    
            }
            else
            {
                for (int i = 0; i < sysWaveItems.Count; i++)
                {
                    string path = relpaceSr(ini.ReadInivalue(sysWaveItems[i].IniName, "DefaultValue"));
                    if (File.Exists(path))
                    {
                        sysWaveItems[i].Custom = "1";
                        sysWaveItems[i].Path = path;
                        isCustomWav = true;
                    }

                }
                listboxSysWaveItems.Items.Refresh();
                if (isCustomWav)
                {
                    chboxDefwav.IsChecked = false;
                    enableWave(true);
                }
            }


        }
        private string relpaceSr(string str)//将%systemroot%转换为实际路径
        {
            return str.ToLower().Replace("%systemroot%",Environment.GetEnvironmentVariable("windir")).Replace("%resourcedir%",Environment.GetEnvironmentVariable("windir")+"\\resources");
            
        }
        private bool fest(string fullname)
        {
            if (File.Exists(fullname))
            { return true; }
            else
                return false;
        }
        private string removeico(string str)
        {
            //MessageBox.Show(str.LastIndexOf(".ico").ToString());
            if (str.LastIndexOf(".ico") < str.Length-4)
                return str.Remove(str.IndexOf(".ico") + 4);
            else
                return str;
            
        }
        private string removedll(string str)
        {
            //MessageBox.Show(str.LastIndexOf(".ico").ToString());
            if (str.LastIndexOf(".dll") < str.Length - 4)
                return str.Remove(str.IndexOf(".dll") + 4);
            else
                return str;

        }
        
        //生成自解压文档（2.0）
        private void saveRar(string filename)
        {
            try
            {
	        //MessageBox.Show(filename);
	        string arg = " a -sfxdefault.sfx \"-z" + tempDir2 + "\"zhushi.txt" + " -r Files *.*";
	        
            if (Directory.Exists(tempDir))
            { Directory.Delete(tempDir, true); }
            if (Directory.Exists(tempDir2))
            { Directory.Delete(tempDir2, true); }
	        creatDir(tempDir);
	        creatDir(tempDir2);
	        writeFile();
	        fileOperate(tempDir);
	        string FILE_NAME = tempDir2 + "zhushi.txt";
	        using (StreamWriter sw = new StreamWriter(new FileStream(FILE_NAME, FileMode.Create), System.Text.Encoding.Default))
	        {
	            string zs = "Path=%SystemRoot%\\resources\\Themes\\\r\n";
	            if (checkboxSaveRarAutoRun.IsChecked.Value)
	                zs += "Setup=\"" + tbFileName.Text + ".theme\"\r\n";
	            if (tbSaveRarTitle.Text != "")
	                zs += "Title=" + tbSaveRarTitle.Text + "\r\n";
	            zs += "Text\r\n{\r\n" + tbSaveRarInfo.Text + "\r\n}\r\n";
	            if (checkboxSaveRarKey.IsChecked.Value)
	                zs += "License=\r\n{\r\n" + tbSaveRarKey.Text + "\r\n}\r\n";
	            sw.Write(zs);
	            sw.Close();
	        }
	
	        var startinfo = new ProcessStartInfo();
	        startinfo.FileName = rarPath;
	        startinfo.Arguments = arg;
            startinfo.WorkingDirectory = tempDir;
	        Process proc = new Process();
	        proc.StartInfo = startinfo;
	        proc.Start();
	        if (proc != null)
	        {
	            proc.WaitForExit();
	        }
	        if (File.Exists(filename))
	            try { File.Delete(filename); }
	            catch (Exception ex) { showErrorWindow(ex.ToString()); }
	        File.Move(tempDir + "Files.exe", filename);
	        Directory.Delete(tempDir, true);
	        Directory.Delete(tempDir2, true);
            }
            catch (System.Exception ex)
            {
                showErrorWindow(ex.ToString());
            }
        }

        //保存读取设置(1.5）
        GenSettings setting = new GenSettings();
        private bool isDef(string str)
        {
            if (str == defcur || str == defico || str == defimg || str == defwav || str == definfo || str == "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private void saveConfig()
        {
            //基本信息
            setting.tbMssfileDir = tbMssfileDir.Text;
            setting.tbLogoDir = tbLogoDir.Text;
            setting.tbInfo = tbInfo.Text;
            setting.tbThemeName = tbThemeName.Text;
            setting.tbFileName = tbFileName.Text;

            //图标
            setting.tbIconComputertfileDir = tbIconComputertfileDir.Text;
            setting.tbIconNetworkDir = tbIconNetworkDir.Text;
            setting.tbIconUserDir = tbIconUserDir.Text;
            setting.tbIconDustEmptyDir = tbIconDustEmptyDir.Text;
            setting.tbIconDustFullDir = tbIconDustFullDir.Text;

            //系统指针
            for (int i = 1; i <= 15; i++)
            {
                setting["tbcur" + i.ToString()] = ((TextBox)FindName("tbcur" + i.ToString())).Text;
            }

            //背景壁纸
            setting.lbWallPaperPlay = null;
            System.Collections.Specialized.StringCollection lbWallPaperPlayStrs = new System.Collections.Specialized.StringCollection(); 
            if (wps.Count != 0)
            {
                
                for (int i = 0; i < wps.Count; i++)
                {
                    lbWallPaperPlayStrs.Add(wps[i].Name);
                }
                setting.lbWallPaperPlay = lbWallPaperPlayStrs;
                setting.cbWallpaperTime = cbWallpaperTime.SelectedIndex;
                setting.cbShuffle = cbShuffle.IsChecked.Value;
                
            }

            //窗口颜色
            try
            {
                Color color2;
                color2 = (Color)ColorConverter.ConvertFromString(tbColorStr.Text);
                rtgColorPan.Fill = new SolidColorBrush(color2);
                setting.tbColorStr = tbColorStr.Text;
            }
            catch { }
            

            //系统音
            System.Collections.Specialized.StringCollection sysWaveTempItemsStr = new System.Collections.Specialized.StringCollection();
            sysWaveTempItemsStr.Clear();
            for (int i = 0; i < sysWaveItems.Count; i++)
            {
                sysWaveTempItemsStr.Add(null);
                sysWaveTempItemsStr[i] = sysWaveItems[i].Path;
            }
            setting.sysWave = sysWaveTempItemsStr;
            setting.chboxDefwav = chboxDefwav.IsChecked.Value;
            setting.cbSysWaveDefaultNum = cbSysWaveDefault.SelectedIndex;

            //自解压框
            setting.checkboxSaveRarKey = checkboxSaveRarKey.IsChecked.Value;
            setting.tbSaveRarKey = tbSaveRarKey.Text;
            setting.tbSaveRarInfo = tbSaveRarInfo.Text;
            setting.checkboxSaveRarAutoRun = checkboxSaveRarAutoRun.IsChecked.Value;
            setting.tbSaveRarTitle = tbSaveRarTitle.Text;
        }
        private void readConfig()
        {
            try
            {
                //基本信息
                if (!isDef(setting.tbMssfileDir))
                    tbMssfileDir.Text = setting.tbMssfileDir;
                if (!isDef(setting.tbLogoDir))
                    tbLogoDir.Text = setting.tbLogoDir;
                if (!isDef(setting.tbInfo))
                    tbInfo.Text = setting.tbInfo;
                if (!isDef(setting.tbThemeName))
                    tbThemeName.Text = setting.tbThemeName;
                if (!isDef(setting.tbFileName))
                    tbFileName.Text = setting.tbFileName;

                //系统图标
                if (!isDef(setting.tbIconComputertfileDir))
                tbIconComputertfileDir.Text = setting.tbIconComputertfileDir;
                if (!isDef(setting.tbIconUserDir))
                tbIconUserDir.Text = setting.tbIconUserDir;
                if (!isDef(setting.tbIconNetworkDir))
                tbIconNetworkDir.Text = setting.tbIconNetworkDir;
                if (!isDef(setting.tbIconDustEmptyDir))
                tbIconDustEmptyDir.Text = setting.tbIconDustEmptyDir;
                if (!isDef(setting.tbIconDustFullDir))
                tbIconDustFullDir.Text = setting.tbIconDustFullDir;
                
                //系统指针
                for (int i = 1; i <= 15; i++)
                {
                    if (!isDef(setting["tbcur" + i.ToString()].ToString()))
                    {
                        ((TextBox)FindName("tbcur" + i.ToString())).Text = (string)setting["tbcur" + i.ToString()];
                        ((TextBox)FindName("tbcur" + i.ToString())).Cursor = new System.Windows.Input.Cursor((string)setting["tbcur" + i.ToString()]);
                    }
                }

                //背景壁纸
                System.Collections.Specialized.StringCollection wpstrs = new System.Collections.Specialized.StringCollection();
                wpstrs = setting.lbWallPaperPlay;
                if (wpstrs != null)
                {
                    for (int i = 0; i < wpstrs.Count;i++ )
                    {
                        if (File.Exists(wpstrs[i]))
                            wps.Add(new WallpaperItems { Name = wpstrs[i], Pic = wpstrs[i] });
                    }
                    if(wpstrs.Count>1)
                    {
                        cbShuffle.IsEnabled = true;
                        cbWallpaperTime.IsEnabled = true;
                    }
                        
                }
                cbShuffle.IsChecked = setting.cbShuffle;
                cbWallpaperTime.SelectedIndex = setting.cbWallpaperTime;
                

                //窗口颜色
                if (setting.tbColorStr != defcolor && setting.tbColorStr != "")
                {
                    paletteColorPic.SelectedColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString(setting.tbColorStr));
                    sliderColor.Value = paletteColorPic.SelectedColor.Color.A / 2.55;
                }
                    

                //系统音
                if (setting.sysWave != null)
                {
                    System.Collections.Specialized.StringCollection sysWaveTempItemsStr = new System.Collections.Specialized.StringCollection();
                    sysWaveTempItemsStr.Clear();
                    sysWaveTempItemsStr = setting.sysWave;
                    for (int i = 0; i < sysWaveTempItemsStr.Count; i++)
                    {
                        if (File.Exists(sysWaveTempItemsStr[i]))
                        {
                            sysWaveItems[i].Custom = "1";
                            sysWaveItems[i].Path = sysWaveTempItemsStr[i];
                            
                        }
                    }
                    
                }
                chboxDefwav.IsChecked = setting.chboxDefwav;
                enableWave(!chboxDefwav.IsChecked.Value);
                cbSysWaveDefault.SelectedIndex = setting.cbSysWaveDefaultNum;

                //自解压框
                checkboxSaveRarKey.IsChecked = setting.checkboxSaveRarKey;
                if (setting.checkboxSaveRarKey)
                    tbSaveRarKey.IsEnabled = true;
                if(setting.tbSaveRarKey!="")
                tbSaveRarKey.Text = setting.tbSaveRarKey;
                if(setting.tbSaveRarInfo !="")
                tbSaveRarInfo.Text = setting.tbSaveRarInfo;
                checkboxSaveRarAutoRun.IsChecked = setting.checkboxSaveRarAutoRun;
                if(setting.tbSaveRarTitle !="")
                tbSaveRarTitle.Text = setting.tbSaveRarTitle;
            }
            catch(Exception ex)
            {
                //throw new System.Exception("", ex);
                showErrorWindow(ex.ToString());
                setDefault();
            }
        }

        //保存提示信息
        private string saveInfo()
        {
            string saveinfo = "";
            
            return saveinfo;
            
        }
        
    }
}



